//
//  UploadView.m
//  ExamSecretary
//
//  Created by mingthink on 16/5/30.
//  Copyright © 2016年 mingthink. All rights reserved.
//

#import "UploadView.h"

@implementation UploadView
//- (id)setFrame:(CGRect)frame currentVC:(UIViewController *)vc
//{
//    return self;
//}
- (void)layoutImageViewsWithCurrentVC:(UIViewController *)vc {
    self.vc = vc;
    
    int imgWidth = self.sideLength;
    int imgHeight = imgWidth;
    int maxImgY = 0;
    int maxImgX = 0;
    _currentImg = 0;
    _arrayImgView = [[NSMutableArray alloc] init]; //初始化imageview数组
    _arrayImgViewDel = [[NSMutableArray alloc] init];
    _arrayImg = [[NSMutableArray alloc] init]; //初始化image数组
    
    _photoGlanceView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVW, DEVH)];
    _photoGlanceView.backgroundColor = [UIColor blackColor];
    
    
    for(int index = 0; index < _MaxImg; index ++)
    {
        //int nextImg = index+1; //下一个图片的个数
        int yIndex = index/_imgCol; //图片在第几行
        int xIndex = index%_imgCol; //图片在第几列
        
        int imgX = (imgWidth+_imgPadding)*xIndex;
        int imgY = (imgHeight+_imgPadding)*yIndex;
        
        if (imgX>maxImgX) maxImgX=imgX;//记录X坐标
        if (imgY>maxImgY) maxImgY=imgY;//记录Y坐标
        //NSLog(@"imgX=%i",imgX);
        //NSLog(@"imgY=%i",imgY);
        UIImageView *imgView =  [[UIImageView alloc] initWithFrame:CGRectMake(imgX, imgY, imgWidth, imgHeight)];
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.clipsToBounds = YES;
        imgView.layer.cornerRadius = 5;
        imgView.userInteractionEnabled = YES;
        UIGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
        [imgView addGestureRecognizer:singleTap];
        
        [_arrayImgView addObject:imgView];
        
        int delW = 20;
        int delH = 20;
        int delX = imgX+imgWidth-delW+3;
        int delY = imgY-3;
        UIImageView *imgViewDel = [[UIImageView alloc] initWithFrame:CGRectMake(delX, delY, delW, delH)];
        imgViewDel.tag = index;
        imgViewDel.image = [UIImage imageNamed:@"deleteimage.png"];
        imgViewDel.userInteractionEnabled = YES;
        
        UIGestureRecognizer *gesDel = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImgDel:)];
        [imgViewDel addGestureRecognizer:gesDel];
        
        [_arrayImgViewDel addObject:imgViewDel];
    }
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, maxImgX + imgWidth,imgHeight);
    [self addImageAddButton];

}
-(void)tapGesture:(UIGestureRecognizer *)tap
{
    //NSLog(@"click=%d",(int)tap.view.tag);
    int selectIndex = (int)tap.view.tag;
    if (selectIndex==_currentImg) {
        //选取
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相册" otherButtonTitles:@"拍照", nil];
        [sheet showInView:self.vc.view];
        
    }
    else {
        //显示
//        [self photoGlance];
//        _photoScroll.contentOffset = CGPointMake(_photoGlanceView.frame.size.width*tap.view.tag, 0);
//        [UIView animateWithDuration:0.6f animations:^{
//            [UIView setAnimationTransition:[_photoGlanceView superview]?UIViewAnimationTransitionFlipFromRight:UIViewAnimationTransitionFlipFromLeft forView:self.vc.view cache:YES];
//            
//            [self.vc.view addSubview:_photoGlanceView];
//            
//        } completion:^(BOOL finished) {
//        }];
    }
}
-(void)photoGlance
{
    [_photoScroll removeFromSuperview];
    NSLog(@"phototGlance");
    int countPhoto = (int)[_arrayImg count];
    _photoScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, DEVW, DEVH)];
    _photoScroll.contentSize = CGSizeMake(countPhoto*_photoScroll.frame.size.width, _photoScroll.frame.size.height);
    
    _photoScroll.pagingEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closePhoto:)];
    [_photoScroll addGestureRecognizer:singleTap];
    
    [_photoGlanceView addSubview:_photoScroll];
    //[photoGlanceView addSubview:cancel];
    _photoScroll.delegate = self;
    
    NSLog(@"countPhoto=%i",countPhoto);
    for (int i = 0; i < countPhoto; i++) {
        
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(i*_photoScroll.frame.size.width, 0, _photoScroll.frame.size.width, _photoScroll.frame.size.height)];
        image.tag = i;
        image.contentMode = UIViewContentModeScaleAspectFit;
        image.image = [_arrayImg objectAtIndex:i];
        //[image sd_setImageWithURL:url];
        //[image setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placed.png"]];
        [_photoScroll addSubview:image];
        
    }
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    CorePhotoPickerVCMangerType type=0;
    if(buttonIndex==0)
        type=CorePhotoPickerVCMangerTypeMultiPhoto;
    //type = CorePhotoPickerVCMangerTypeSinglePhoto;
    else if(buttonIndex==1)
        type=CorePhotoPickerVCMangerTypeCamera;
    //    else if(buttonIndex==2)
    //        type=CorePhotoPickerVCMangerTypeVideo;
    else if(buttonIndex>1) //取消
        return;
    
    CorePhotoPickerVCManager *manager=[CorePhotoPickerVCManager sharedCorePhotoPickerVCManager];
    
    //设置类型
    manager.pickerVCManagerType=type;
    
    //最多可选10张
    manager.maxSelectedPhotoNumber=_MaxImg-_currentImg;
    
    //错误处理
    if(manager.unavailableType!=CorePhotoPickerUnavailableTypeNone){
        NSLog(@"设备不可用");
        //        NSString *strMsg = @"设备不可用";
        //        [self.view makeToast:strMsg];
        return;
    }
    
    UIViewController *pickerVC=manager.imagePickerController;
    
#pragma mark 返回图片
    //选取结束
    manager.finishPickingMedia=^(NSArray *medias){
        
        NSLog(@"medias.count=%lu",(unsigned long)medias.count);
        
        [medias enumerateObjectsUsingBlock:^(CorePhoto *photo, NSUInteger idx, BOOL *stop) {
            //NSLog(@"%@",photo);
            
            UIImage *tempImg = photo.editedImage;
            //把图片保存到数组
            [_arrayImg addObject:tempImg];
            
            UIImageView *curImg = [_arrayImgView objectAtIndex:_currentImg];
            curImg.image = tempImg;
            //            curImg.contentMode = UIViewContentModeScaleAspectFill;
            //            curImg.clipsToBounds = YES;
            [self addSubview:curImg];
            
            curImg.tag = _currentImg;
            //            curImg.userInteractionEnabled = YES;
            //            UIGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
            //            [curImg addGestureRecognizer:singleTap];
            
            UIImageView *curImgDel = [_arrayImgViewDel objectAtIndex:_currentImg];
            //curImgDel.image = [UIImage imageNamed:@"删除.png"];
            [self addSubview:curImgDel];
            
            _currentImg++;
            [self addImageAddButton]; //增加+按钮
        }];
    };
    
    [self.vc presentViewController:pickerVC animated:YES completion:nil];
    
}
- (void)closePhoto:(UIGestureRecognizer *)gestureRecognizer {
    [UIView animateWithDuration:0.6f animations:^{
        [UIView setAnimationTransition:[_photoGlanceView superview]?UIViewAnimationTransitionFlipFromRight:UIViewAnimationTransitionFlipFromLeft forView:self.vc.view cache:YES];
        
        [_photoGlanceView removeFromSuperview];
        
    } completion:^(BOOL finished) {}];
}

- (void)addImageAddButton {
    if (_currentImg>=_MaxImg) {
        //当前图片数超过总数
        return;
    }
    UIImageView *curImg = [_arrayImgView objectAtIndex:_currentImg];
    curImg.image = [UIImage imageNamed:@"addimage.png"];
    [self addSubview:curImg];
    
    curImg.tag = _currentImg;
    curImg.userInteractionEnabled = YES;
    UIGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
    [curImg addGestureRecognizer:singleTap];

    //调用代理方法
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, CGRectGetMaxY(curImg.frame));
    [_delegate uploadView:self changeSizeHeight:CGRectGetMaxY(self.frame) - _sideLength];

    //currentImg++;
}
-(void)tapImgDel:(UIGestureRecognizer *)tap
{
    int tag = (int)tap.view.tag;
    
    [_arrayImg removeObjectAtIndex:tag];
    
    [self refreshUI];
    //    UIImageView *curImg = [arrayImgView objectAtIndex:tag];
    //    [curImg removeFromSuperview];
    //
    //    UIImageView *curImgDel = [arrayImgViewDel objectAtIndex:tag];
    //    [curImgDel removeFromSuperview];
    //    currentImg--;
    //
    //    UIImageView *curImgAdd = [arrayImgView objectAtIndex:tag+1];
    //    [curImgAdd removeFromSuperview];
    //
    //    [self addImageAddButton]; //增加+按钮
}
- (void)refreshUI {
    for(int index = 0; index < _MaxImg; index ++) {
        UIImageView *curImg = [_arrayImgView objectAtIndex:index];
        [curImg removeFromSuperview];
        
        UIImageView *curImgDel = [_arrayImgViewDel objectAtIndex:index];
        [curImgDel removeFromSuperview];
    }
    
    _currentImg = _arrayImg.count;
    for(int index = 0; index < _currentImg; index ++) {
        UIImageView *curImg = [_arrayImgView objectAtIndex:index];
        curImg.image = [_arrayImg objectAtIndex:index];
        [self addSubview:curImg];
        
        UIImageView *curImgDel = [_arrayImgViewDel objectAtIndex:index];
        [self addSubview:curImgDel];
    }
    [self addImageAddButton];

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
